//package com.example.nep.util;
//
//import com.example.xuanke01.base.R;
//import com.example.xuanke01.dao.PowerMapper;
//import com.example.xuanke01.model.*;
//import com.example.xuanke01.vo.UserVO;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.PrintWriter;
//import java.util.List;
//
///**
// * @Author: 韩建平
// * @Description: TODO
// * @DateTime: 2024/4/7 14:23
// **/
//@Component
//public class JWTInterceptor implements HandlerInterceptor {
//    @Resource
//    private PowerMapper powerMapper;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 允许跨域
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        // 允许自定义请求头token(允许head跨域)
//        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
//        //后台管理页面产生的token
//        String token = request.getHeader("token");
//        // 检查token是否存在
//        if (token == null) {
//            PrintWriter writer = response.getWriter();
//            writer.print(R.error().setCode(201).setMsg("token不存在"));
//            return false;
//        } else {
//            UserVO userVO = JwtUtil.checkToken(token);
//            if (userVO == null) {
//                PrintWriter writer = response.getWriter();
//                writer.print(R.error().setCode(202).setMsg("用户不存在"));
//                throw new RuntimeException("用户不存在");
//            }
//            int userId = userVO.getId();
//            List<Power> powers = powerMapper.selectPowerByUserId(userId);
//            boolean flag = false;
//            String url = request.getRequestURI();
//            String method = request.getMethod();
//            for (Power power : powers) {
//                if (power.getUrl().equals(url) && power.getMethod().equals(method)) {
//                    flag = true;
//                    break;
//                }
//            }
//            if (flag) {
//                return true;
//            } else {
//                PrintWriter writer = response.getWriter();
//                writer.print(R.error().setCode(203).setMsg("权限不足"));
//                return false;
//            }
//        }
//    }
//}
